<template>
  <div>
    <!-- 面包屑导航 -->
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>权限管理</el-breadcrumb-item>
      <el-breadcrumb-item>角色列表</el-breadcrumb-item>
    </el-breadcrumb>
    <!-- 卡片区域 -->
    <el-card>
      <el-row>
        <el-col>
          <el-button type="primary" plain @click="addRoleDialog = true">添加角色</el-button>
        </el-col>
      </el-row>
      <!-- 角色列表表格区域 -->
      <el-table :data="rolesList" style="width: 100%" border stripe>
        <!-- 列表展开区域 -->
        <el-table-column type="expand">
          <template slot-scope="scope">
            <!-- 用v-for遍历数据渲染权限 -->
            <el-row
              :class="['bbottom','vcenter',i1 === 0 ? 'btop' : '']"
              v-for="(item1,i1) in scope.row.children"
              :key="item1.id"
            >
              <!-- 一级权限渲染 -->
              <el-col :span="5">
                <el-tag
                  size="medium"
                  closable
                  @close="removeRightsById(scope.row,item1.id)"
                >{{item1.authName}}</el-tag>
                <i class="el-icon-caret-right"></i>
              </el-col>
              <!-- 渲染二级和三级权限 -->
              <el-col :span="19">
                <el-row
                  :class="[i2 === 0 ? '' : 'btop', 'vcenter']"
                  v-for="(item2,i2) in item1.children"
                  :key="item2.id"
                >
                  <!-- 渲染二级权限 -->
                  <el-col :span="6">
                    <el-tag
                      size="medium"
                      type="success"
                      closable
                      @close="removeRightsById(scope.row,item2.id)"
                    >{{item2.authName}}</el-tag>
                    <i class="el-icon-caret-right"></i>
                  </el-col>
                  <!-- 渲染三级权限 -->
                  <el-col :span="18">
                    <el-tag
                      size="medium"
                      type="warning"
                      v-for="item3 in item2.children"
                      :key="item3.id"
                      closable
                      @close="removeRightsById(scope.row,item3.id)"
                    >{{item3.authName}}</el-tag>
                  </el-col>
                </el-row>
              </el-col>
            </el-row>
            <!-- <pre>
                 {{scope.row}}
            </pre>-->
          </template>
        </el-table-column>
        <!-- 索引区域 -->
        <el-table-column align="center" type="index" label="#"></el-table-column>
        <el-table-column align="center" prop="roleName" label="角色管理"></el-table-column>
        <el-table-column align="center" prop="roleDesc" label="角色描述"></el-table-column>
        <el-table-column align="center" label="操作">
          <template slot-scope="scope">
            <el-button
              size="mini"
              plain
              type="success"
              icon="el-icon-edit"
              @click="editRolesList(scope.row.id)"
            >编辑</el-button>
            <el-button
              size="mini"
              plain
              type="danger"
              icon="el-icon-delete"
              @click="removeRoles(scope.row.id)"
            >删除</el-button>
            <el-button
              size="mini"
              plain
              type="warning"
              icon="el-icon-setting"
              @click="setRights(scope.row)"
            >分配权限</el-button>
          </template>
        </el-table-column>
      </el-table>
    </el-card>
    <!-- 增加添加角色的对话框 -->
    <el-dialog title="添加角色" :visible.sync="addRoleDialog" width="30%" @close="addRolesClear">
      <!-- 输入框区域 -->
      <el-form ref="rolesFormRef" :model="rolesForm" :rules="rolesFormRules" label-width="80px">
        <el-form-item label="角色名称" prop="roleName">
          <el-input v-model="rolesForm.roleName"></el-input>
        </el-form-item>
        <el-form-item label="角色描述" prop="roleDesc">
          <el-input v-model="rolesForm.roleDesc"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="addRoleDialog = false">取 消</el-button>
        <el-button type="primary" @click="addRoles">确 定</el-button>
      </span>
    </el-dialog>
    <!-- 添加编辑角色的对话框 -->
    <el-dialog title="编辑角色" :visible.sync="editRolesDialog" width="50%" @close="editRolesClear">
      <el-form
        ref="editRolesFormRef"
        :model="editRolesForm"
        :rules="editRolesFormRules"
        label-width="80px"
      >
        <el-form-item label="角色名称" prop="roleName">
          <el-input v-model="editRolesForm.roleName"></el-input>
        </el-form-item>
        <el-form-item label="角色描述" prop="roleDesc">
          <el-input v-model="editRolesForm.roleDesc"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="editRolesDialog = false">取 消</el-button>
        <el-button type="primary" @click="editRoles">确 定</el-button>
      </span>
    </el-dialog>
    <!-- 添加分配权限的对话框 -->
    <el-dialog
      title="分配权限"
      :visible.sync="setRightsDialogVisible"
      width="50%"
      @close="setRightsLeafkeys"
    >
      <!-- 展示树组件 -->
      <el-tree
        :data="setRightList"
        :props="treeProps"
        node-key="id"
        show-checkbox
        default-expand-all
        :default-checked-keys="lefKeys"
        ref="treeRef"
      ></el-tree>
      <span slot="footer" class="dialog-footer">
        <el-button @click="setRightsDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="allowRole">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
export default {
  name: 'Roles',
  data() {
    return {
      // 定义一个渲染列表的数组
      rolesList: [],
      // 定义一个角色数据数组
      rolesForm: {
        roleName: '',
        roleDesc: ''
      },
      // 定义一个添加用户角色的验证规则
      rolesFormRules: {
        roleName: [
          { required: true, message: '请输入角色名称', trigger: 'blur' },
          { min: 3, max: 10, message: '长度在 3 到 10 个字符', trigger: 'blur' }
        ],
        roleDesc: [
          { required: true, message: '请输入角色描述', trigger: 'blur' },
          { min: 3, max: 10, message: '长度在 3 到 10 个字符', trigger: 'blur' }
        ]
      },
      // 定义一个添加角色对话框的显示与隐藏
      addRoleDialog: false,
      // 定义一个接收分配权限数据的数组
      // 编辑角色的信息定义的对象
      editRolesForm: {},
      // 定义一个编辑角色对话的显示和隐藏
      editRolesDialog: false,
      // 编辑验证规则
      editRolesFormRules: {
        roleName: [
          { required: true, message: '请输入角色名称', trigger: 'blur' },
          { min: 3, max: 10, message: '长度在 3 到 10 个字符', trigger: 'blur' }
        ],
        roleDesc: [
          { required: true, message: '请输入角色描述', trigger: 'blur' },
          { min: 3, max: 10, message: '长度在 3 到 10 个字符', trigger: 'blur' }
        ]
      },
      setRightList: [],
      // 定义一个分配权限默认弹框的显示与隐藏
      setRightsDialogVisible: false,
      // 定义树组件展示对象的内容
      treeProps: {
        label: 'authName',
        children: 'children'
      },
      // 默认选中的节点id值
      lefKeys: [],
      // 当前要分配的权限id
      roleId: ''
    }
  },
  created() {
    // 获取调用角色列表方法
    this.getRolesList()
  },
  methods: {
    // 定义一个获取角色列表方法
    async getRolesList() {
      const { data: res } = await this.$http.get('/roles')
      if (res.meta.status !== 200) return this.$message.error(res.meta.msg)
      // 成功之后赋值给定义的角色数组
      this.rolesList = res.data
      console.log(this.rolesList)
    },

    // 关闭对话框 清空表单
    addRolesClear() {
      this.$refs.rolesFormRef.resetFields()
    },

    // 添加角色的方法 点击添加按钮打开对话框
    addRoles() {
      // 先进行验证
      this.$refs.rolesFormRef.validate(async valid => {
        // console.log(valid)
        if (!valid) return
        const { data: res } = await this.$http.post('/roles', this.rolesForm)
        if (res.meta.status !== 201) return this.$message.error(res.meta.msg)
        this.getRolesList()
        this.addRoleDialog = false
      })
    },

    // 关闭对话框 清空编辑表单
    editRolesClear() {
      this.$refs.editRolesFormRef.resetFields()
    },

    // 先根据id获取角色信息
    async editRolesList(id) {
      console.log(id)
      const { data: res } = await this.$http.get(`/roles/${id}`)
      if (res.meta.status !== 200) return this.$message.error(res.meta.msg)
      this.editRolesForm = res.data
      this.editRolesDialog = true
    },

    // 根据赋值后的表单更改数据
    editRoles() {
      this.$refs.editRolesFormRef.validate(async valid => {
        // console.log(valid)
        if (!valid) return
        const { data: res } = await this.$http.put(`/roles/${this.editRolesForm.roleId}`, {
          roleName: this.editRolesForm.roleName,
          roleDesc: this.editRolesForm.roleDesc
        })
        if (res.meta.status !== 200) return this.$message.error(res.meta.msg)
        this.$message.success(res.meta.msg)
        this.getRolesList()
        this.editRolesDialog = false
      })
    },

    // 删除用户角色
    async removeRoles(id) {
      const removeConfirm = await this.$confirm('此操作将永久删除该用户, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).catch(err => err)
      if (removeConfirm !== 'confirm') return this.$message.info('您已取消删除')
      const { data: res } = await this.$http.delete(`/roles/${id}`)
      if (res.meta.status !== 200) return this.$message.error(res.meta.msg)
      this.getRolesList()
    },

    // 移除权限
    async removeRightsById(role, rightId) {
      const confirmResult = await this.$confirm('此操作将永久删除该权限, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).catch(err => err)
      if (confirmResult !== 'confirm') return this.$message.info('您取消了删除')
      console.log(role.id, rightId)
      const { data: res } = await this.$http.delete(`/roles/${role.id}/rights/${rightId}`)
      if (res.meta.status !== 200) return this.$message.error(res.meta.msg)
      // 成功之后 只需要局部刷新权限
      role.children = res.data
    },

    // 定义一个分配权限的方法，先获取数据
    async setRights(role) {
      // console.log(role)
      this.roleId = role.id
      const { data: res } = await this.$http.get('/rights/tree')
      if (res.meta.status !== 200) return this.$message.error(res.meta.msg)
      this.setRightList = res.data
      // 递归获取三级节点的id
      this.getleafKeys(role, this.lefKeys)
      this.setRightsDialogVisible = true
    },

    // 定义一个递归的方法获取到所有三级权限的id 保存到defKey保存三级权限id的数组中 通过递归方式获取所有的三级权限菜单
    getleafKeys(node, arr) {
      // 因为三级权限菜单是没有children的 所以可以根据这个去判断 是否是三级菜单
      if (!node.children) return arr.push(node.id)
      // 然后再去遍历数组
      node.children.forEach(item => {
        this.getleafKeys(item, arr)
      })
    },

    // 点击关闭对话框 清空leafKeys
    setRightsLeafkeys() {
      this.lefKeys = []
    },

    // 点击确定分配权限
    async allowRole() {
      // 现获取节点和半节点的id
      const keys = [...this.$refs.treeRef.getCheckedKeys(), ...this.$refs.treeRef.getHalfCheckedKeys()]
      // console.log(keys)
      const keysStr = keys.join(',')
      // 发送请求
      const { data: res } = await this.$http.post(`roles/${this.roleId}/rights`, {
        rids: keysStr
      })
      if (res.meta.status !== 200) return this.$message.error(res.meta.msg)
      // 成功之后
      this.$message.success(res.meta.msg)
      this.getRolesList()
      this.setRightsDialogVisible = false
    }
  }
}
</script>

<style lang="less" scoped>
// 标签样式
.el-tag {
  margin: 8px;
}

.btop {
  border-top: 1px solid #eee;
}
.bbottom {
  border-bottom: 1px solid #eee;
}
.vcenter {
  display: flex;
  align-items: center;
}
</style>
